// Copyright (c) 2010 Manuel Peinado Gallego <manuel.peinado@gmail.com>
// Distributed under the MIT license


#include "stdafx.h"
#include "WorldBuilder.h"
#include "View3d.h"
#include "Drawable.h"


WorldFollower::WorldFollower(int flags)
: m_world(NULL), m_flags(flags)
{
}

WorldFollower::~WorldFollower()
{
    // TODO use RAII!!
    if(m_world)
    {
        if((m_flags & WorldFollower::IsNodeListener) != 0)
        {
            m_world->getNodeManager().removeNodeListener(this);
        }
        if((m_flags & WorldFollower::IsMaterialListener) != 0)
        {
            m_world->getMaterialManager().removeMaterialListener(this);
        }
        if((m_flags & WorldFollower::IsShaderListener) != 0)
        {
            m_world->getShaderManager().removeShaderListener(this);
        }
        if((m_flags & WorldFollower::IsTextureListener) != 0)
        {
            m_world->getTextureManager().removeTextureListener(this);
        }
        if((m_flags & WorldFollower::IsMeshListener) != 0)
        {
            m_world->getMeshManager().removeMeshListener(this);
        }
    }
}

// -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  

World& WorldFollower::getWorld()
{
    ASSERT(m_world != NULL);
    return* m_world;
}

bool WorldFollower::hasWorld() const
{
    return m_world != NULL;
}

void WorldFollower::setWorld(World* world)
{
    m_world = world;
    
    if(m_world)
    {
        if((m_flags & WorldFollower::IsNodeListener) != 0)
        {
            m_world->getNodeManager().addNodeListener(this);
        }
        if((m_flags & WorldFollower::IsMaterialListener) != 0)
        {
            m_world->getMaterialManager().addMaterialListener(this);
        }
        if((m_flags & WorldFollower::IsShaderListener) != 0)
        {
            m_world->getShaderManager().addShaderListener(this);
        }
        if((m_flags & WorldFollower::IsTextureListener) != 0)
        {
            m_world->getTextureManager().addTextureListener(this);
        }
        if((m_flags & WorldFollower::IsMeshListener) != 0)
        {
            m_world->getMeshManager().addMeshListener(this);
        }
    }

    onWorldChanged(world);
}
